/**
 * Created by 86177 on 2019/7/30.
 */

var writeDealJson = [];
var readDealJson = [];
var blockJson = [];
var dealChart = null;
var blockChart = null;
var maxWriteDeal = 0;
var maxReadDeal = 0;
$(function () {
    initTop();
    initUI();
    initMessage();
    initTopLine();
    initBar();
});

function initUI() {
    $(".page-bottom").css("height", window.innerHeight - $(".page-header").height() - $(".page-top").height() + "px");

    $(".header-tip").click(function () {
        layui.use(['layer', 'element'], function () {
            var layer = layui.layer;
            layer.open({
                type: 1,
                title: '搜索区块信息',
                area: ['700px', '400px'],
                shadeClose: false,
                content: $("#searchHtml").html(),
                success: function () {
                    $(document).keyup(function (event) {
                        if (event.keyCode == 13) {
                            $("#searchBtn").trigger("click");
                        }
                    });
                    $("#searchBtn").click(function () {
                        if ($("#type").val() == "-1") {
                            layer.msg("请选择查询条件！");
                            return false;
                        }
                        if ($("#serachVal").val() == "") {
                            layer.msg("请输入查询条件！");
                            return false;
                        }
                        var url = "http://49.234.46.85:9002/?AppCode=storage&Action=Block.Get";
                        if ($("#type").val() == "0") {
                            url = url + "&BlockNumber=" + $("#serachVal").val();
                        } else if ($("#type").val() == "1") {
                            url = url + "&BlockHash=" + $("#serachVal").val();
                        } else if ($("#type").val() == "1") {
                            url = url + "&TransactionID=" + $("#serachVal").val();
                        }
                        $.ajax({
                            type: 'get',
                            url: url,
                            // dataType: "jsonp",
                            // jsonp: "callback",
                            success: function (obj) {
                                $(".search-content").show();
                                var data = JSON.parse(obj).Data;
                                for (var key in data) {
                                    $("#" + key).html(data[key]);
                                    if (key == "Timestamp") {
                                        $("#" + key).html(new Date(data[key] * 1000).format("yyyy-MM-dd hh:mm:ss"));
                                    } else if (key == "Envelopes") {
                                        var arr = data[key];
                                        var _html = [];
                                        for (var i = 0; i < arr.length; i++) {
                                            _html.push('<div class="envelopes-item">');
                                            _html.push('<div class="envelopes-line">');
                                            _html.push('<div class="envelopes-tip">(' + (i + 1) + ')</div>');
                                            _html.push('<div class="envelopes-left">');
                                            _html.push('<div class="envelopes-val">交易ID：' + arr[i].TransactionID + '</div></div></div>');
                                            _html.push('<div class="envelopes-line">');
                                            _html.push('<div class="envelopes-tip" style="opacity: 0;">(' + (i + 1) + ')</div>');
                                            _html.push('<div class="envelopes-right">');
                                            _html.push('<div class="envelopes-val">交易时间：' + new Date(arr[i].Timestamp * 1000).format("yyyy-MM-dd hh:mm:ss") + '</div></div></div>');
                                            _html.push('<div class="envelopes-line">');
                                            _html.push('<div class="envelopes-tip" style="opacity: 0;">(' + (i + 1) + ')</div>');
                                            _html.push('<div class="envelopes-left">');
                                            var type = parseInt(arr[i].Type);
                                            switch (type) {
                                                case 0:
                                                    type = "MESSAGE";
                                                    break;
                                                case 1:
                                                    type = "CONFIG";
                                                    break;
                                                case 2:
                                                    type = "CONFIG_UPDATE";
                                                    break;
                                                case 3:
                                                    type = "ENDORSER_TRANSACTION";
                                                    break;
                                                case 4:
                                                    type = "ORDERER_TRANSACTION";
                                                    break;
                                                case 5:
                                                    type = "DELIVER_SEEK_INFO";
                                                    break;
                                                case 6:
                                                    type = "CHAINCODE_PACKAGE";
                                                    break;
                                                case 8:
                                                    type = "PEER_ADMIN_OPERATION";
                                                    break;
                                            }
                                            _html.push('<div class="envelopes-val">交易类型：' + type + '</div></div></div>');
                                            _html.push('<div class="envelopes-line">');
                                            _html.push('<div class="envelopes-tip" style="opacity: 0;">(' + (i + 1) + ')</div>');
                                            _html.push('<div class="envelopes-right">');
                                            _html.push('<div class="envelopes-val">交易内容：' + arr[i].Data + '</div></div></div>');
                                        }
                                        $("#" + key).html(_html.join(""));
                                    }
                                }
                            },
                            error: function (data) {
                                layer.msg("系统错误，请重试！");
                            },
                            complete: function (data) {
                                if (data.status != 200) {
                                    layer.msg("参数无效！");
                                }
                            }
                        });
                    });
                }
            });
        });
    })


}


function initTop() {
    var ws = null;
    ws = new WebSocket('ws://49.234.46.85:9002/?Action=Monitor.Core&AppCode=storage');
    ws.onopen = function () {
        console.log("客户端已连接");
    };
    ws.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        for (var i = 0; i < data.length; i++) {
            $(".top-val:eq(" + i + ")").html(data[i]);
        }
    };
    ws.onclose = function () {
        console.log("客户端已断开连接");
    };
    ws.onerror = function (evt) {
        console.log(evt.data);
    };
}

function initMessage() {
    var ws = null;
    ws = new WebSocket('ws://49.234.46.85:9002/?Action=Monitor.Info&AppCode=storage');
    ws.onopen = function () {
        console.log("客户端已连接");
    };
    ws.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        for (var i = 0; i < data.length; i++) {
            $(".left-val:eq(" + i + ")").html(data[i]);
            if (i == 4) {
                $(".left-val:eq(" + i + ")").html(new Date(data[i] * 1000).format("yyyy-MM-dd hh:mm:ss"));
            }
        }
    };
    ws.onclose = function () {
        console.log("客户端已断开连接");
    };
    ws.onerror = function (evt) {
        console.log(evt.data);
    };
}

function initTopLine() {
    var timestamp = new Date().getTime();
    var id = "topLine_" + timestamp;
    $(".top-box").html('<div id="' + id + '" style="width:100%;height:100%"></div>');
    var xAxis = [];
    var legend = ['写TPS', '读TPS'];
    var series = [];
    var colorArr = [
        {
            colorBegin: 'rgba(59,216,169,1)',
            colorEnd: 'rgba(59,216,169,0)'
        },
        {
            colorBegin: 'rgba(174,121,252,1)',
            colorEnd: 'rgba(174,121,252,0)'
        }
    ];
    for (var m = 0; m < 2; m++) {
        series.push({
            name: legend[m],
            type: 'line',
            smooth: true,
            lineStyle: {
                normal: {
                    color: colorArr[m].colorBegin
                }
            },
            data: []
        });
    }
    var param = {
        series: series,
        legend: legend,
        xAxis: xAxis
    };
    setTopLine(param, id);
    var ws = null;
    ws = new WebSocket('ws://49.234.46.85:9002/?Action=Monitor.Transaction&AppCode=storage');
    ws.onopen = function () {
        console.log("客户端已连接");
    };
    ws.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        var time = new Date().getTime();
        maxWriteDeal = data[0];
        maxReadDeal = data[1];
        writeDealJson.push([time, data[2]]);
        readDealJson.push([time, data[3]]);
        if (writeDealJson.length > 40) {
            writeDealJson.shift();
        }
        if (readDealJson.length > 40) {
            readDealJson.shift();
        }
        $("#maxWrite").html("写峰值：" + maxWriteDeal);
        $("#maxRead").html("读峰值：" + maxReadDeal);
        $("#writeTime").html("写平均响应时间：" + data[4]);
        $("#readTime").html("读平均响应时间：" +data[5]);
        dealChart.setOption({
            series: [
                {
                    type: 'line',
                    data: writeDealJson
                },
                {
                    type: 'line',
                    data: readDealJson
                }
            ]
        });
    };
    ws.onclose = function () {
        console.log("客户端已断开连接");
    };
    ws.onerror = function (evt) {
        console.log(evt.data);
    };

}
function setTopLine(param, id) {
    dealChart = echarts.init(document.getElementById(id));
    var option = {
        title: {
            text: '交易读写速度',
            textStyle: {
                color: '#fff',
                fontSize: 16,
                fontWeight: "normal"
            },
            left: 'center'
        },
        color: ['rgba(59,216,169,1)', 'rgba(174,121,252,1)'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        legend: {
            data: param.legend,
            textStyle: {
                color: '#fff'
            },
            bottom: 0
        },
        grid: {
            left: '10px',
            right: '20px',
            top: '30px',
            bottom: '30px',
            containLabel: true
        },
        xAxis: [
            {
                type: 'time',
                boundaryGap: false,
                nameTextStyle: {
                    color: '#fff'
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    color: '#fff',
                    formatter: function (value) {
                        var t_date = new Date(value);
                        // return [t_date.getFullYear(), t_date.getMonth() + 1, t_date.getDate()].join('/') + " "
                        //     + [t_date.getHours(), t_date.getMinutes()].join(':');
                        return [[t_date.getHours(), t_date.getMinutes(), t_date.getSeconds()].join(':')];
                    }
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                nameTextStyle: {
                    color: '#fff'
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    color: '#fff'
                }
            }
        ],
        series: param.series
    };
    dealChart.setOption(option);
}

function initBar() {
    var timestamp = new Date().getTime();
    var id = "topBar_" + timestamp;
    $(".bottom-box").html('<div id="' + id + '" style="width:100%;height:100%"></div>');
    var param = {
        list: []
    };
    setBar(param, id);
    var ws = null;
    ws = new WebSocket('ws://49.234.46.85:9002/?Action=Monitor.Block&AppCode=storage');
    ws.onopen = function () {
        console.log("客户端已连接");
    };
    ws.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        var time = new Date().getTime();
        blockJson.push([time, data[0]]);
        $("#maxBlock").html("出块峰值：" + data[1]);
        if (blockJson.length > 40) {
            blockJson.shift();
        }
        blockChart.setOption({
            series: [
                {
                    type: 'line',
                    data: blockJson
                }]
        });
    };
    ws.onclose = function () {
        console.log("客户端已断开连接");
    };
    ws.onerror = function (evt) {
        console.log(evt.data);
    };
}
function setBar(param, id) {
    blockChart = echarts.init(document.getElementById(id));
    var option = {
        title: {
            text: '区块速度',
            textStyle: {
                color: '#fff',
                fontSize: 16,
                fontWeight: "normal"
            },
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '10px',
            right: '20px',
            top: '30px',
            bottom: '10px',
            containLabel: true
        },
        xAxis: {
            type: 'time',
            nameTextStyle: {
                color: '#fff'
            },
            axisLine: {
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#fff',
                axisLabel: {
                    color: '#fff',
                    formatter: function (value) {
                        var t_date = new Date(value);
                        // return [t_date.getFullYear(), t_date.getMonth() + 1, t_date.getDate()].join('/') + " "
                        //     + [t_date.getHours(), t_date.getMinutes()].join(':');
                        return [[t_date.getHours(), t_date.getMinutes(), t_date.getSeconds()].join(':')];
                    }
                }
            },
            splitLine: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            minInterval: 10,
            splitNumber: 5,
            nameTextStyle: {
                color: '#fff'
            },
            axisLine: {
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                color: '#fff'
            }
        },
        series: [{
            data: param.list,
            type: 'line',
            barWidth: 15,
            itemStyle: {
                normal: {
                    barBorderRadius: [10, 10, 0, 0],
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: "#00FFE3"
                    },
                        {
                            offset: 1,
                            color: "#4693EC"
                        }
                    ])
                }
            }
        }]
    };
    blockChart.setOption(option);
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };

    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};